import cookies from './util.cookies'
import db from './util.db'
import log from './util.log'
import helper from './util.helper'
import jsencrypt from './util.jsencrypt'
const util = {
  cookies,
  db,
  log,
  helper,
  jsencrypt,
  import: require('./util.import.' + process.env.NODE_ENV)
}

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function (titleText) {
  const processTitle = process.env.VUE_APP_TITLE || 'ycAdmin'
  window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'ycAdmin-link-temp')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('ycAdmin-link-temp'))
}

util.parseTime = function (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'undefined' || time === null || time === 'null') {
    return ''
  } else if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    // eslint-disable-next-line standard/computed-property-even-spacing
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

util.cloneObject = (obj) => {
  return JSON.parse(JSON.stringify(obj))
}

/**
 *@description判断object是否有效
 * @return boolean
 */
util.isVaild = (obj) => {
  if (typeof (obj) === 'undefined') {
    return false
  }
  if (obj === null) {
    return false
  }

  if (JSON.stringify(obj) === '{}') {
    return false
  }
  if (JSON.stringify(obj) === '[]') {
    return false
  }
  if (obj === '') {
    return false
  }
  return true
}

util.treeData = (source, id = 'id', parentId = 'parentId', children = 'children', sort = 'sort') => {
  if (util.isVaild(source)) {
    let cloneData = JSON.parse(JSON.stringify(source))
    return cloneData.filter(father => {
      let branchArr = cloneData
        .filter(child => father[id] === child[parentId])
        .sort((x, y) => {
          return x[sort] - y[sort]
        })
      // eslint-disable-next-line no-unused-expressions
      branchArr.length > 0 ? father[children] = branchArr : ''
      return father[parentId] === 0// 如果第一层不是parentId=0，请自行修改
    }).sort((x, y) => {
      return x[sort] - y[sort]
    })
  } else {
    return []
  }
}

util.flattenData = (source, children = 'children') => {
  let res = []
  source.forEach((item) => {
    res.push(item)
    if (item[children]) {
      res.push(...util.flattenData(item[children]))
    }
  })
  return res
}

util.objectToFormData = (data) => {
  let formData = new FormData()
  Object.keys(data).map(key => {
    formData.append(key, data[key])
  })
  return formData
}

// 下载文件
util.downloadFile = (obj, name, suffix) => {
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = util.parseTime(new Date()) + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 精确小数点
// number：为你要转换的数字
// format：要保留几位小数；譬如要保留2位，则值为2
// zerFill:是否补零。不需要补零可以不填写此参数
util.accurateDecimal = (number, format, zeroFill) => {
  // 判断非空
  if (!util.isEmpty(number)) {
    // 正则匹配:正整数，负整数，正浮点数，负浮点数
    if (!/^\d+(\.\d+)?$|^-\d+(\.\d+)?$/.test(number)) { return number }
    var n = 1
    for (var i = 0; i < format; i++) {
      n = n * 10
    }

    // 四舍五入
    number = Math.round(number * n) / n
    var str = number.toString()

    // 是否补零
    if (zeroFill) {
      var index
      if (str.indexOf('.') === -1) {
        index = format
        str += '.'
      } else {
        index = format - ((str.length - 1) - str.indexOf('.'))
      }

      for (let i = 0; i < index; i++) {
        str += '0'
      }
    }
    return str
  }
  return number
}
// 非空验证
util.isEmpty = (ObjVal) => {
  if ((ObjVal == null || typeof (ObjVal) === 'undefined') || (typeof (ObjVal) === 'string' && ObjVal === '' && ObjVal !== 'undefined')) {
    return true
  } else {
    return false
  }
}

util.converSize = (limit) => {
  var size = ''
  if (limit < 0.1 * 1024) { // 如果小于0.1KB转化成B
    size = limit.toFixed(2) + 'B'
  } else if (limit < 0.1 * 1024 * 1024) { // 如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + 'KB'
  } else if (limit < 0.1 * 1024 * 1024 * 1024) { // 如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
  } else { // 其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }

  var sizestr = size + ''
  var len = sizestr.indexOf('\\.')
  var dec = sizestr.substr(len + 1, 2)
  if (dec === '00') { // 当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
  }
  return sizestr
}

util.uuid = () => {
  var d = new Date().getTime()
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
  return uuid
}

export default util
